import { ElMessage } from 'element-plus'
import { useUserStore } from '../store/user'

interface RequestOptions extends RequestInit {
  url: string;
  method?: string;
  data?: any;
  params?: Record<string, any>;
}

// 创建请求实例
const request = async (options: RequestOptions | string) => {
  const userStore = useUserStore()
  
  // 默认配置
  const defaultOptions: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization, token'
    },
    credentials: 'include',
    mode: 'cors'
  }

  // 如果有token，添加到请求头以适配 sa-token 框架
  if (userStore.token) {
    defaultOptions.headers = {
      ...defaultOptions.headers,
      'token': userStore.token
    }
  }

  try {
    let url: string;
    let requestOptions: RequestInit = {};

    if (typeof options === 'string') {
      url = options;
    } else {
      url = options.url;
      const { url: _, data, params, ...rest } = options;
      requestOptions = rest;

      // 处理请求体
      if (data) {
        requestOptions.body = JSON.stringify(data);
      }

      // 处理URL参数
      if (params) {
        const queryString = Object.entries(params)
          .filter(([_, value]) => value !== undefined && value !== null)
          .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
          .join('&');
        if (queryString) {
          url += (url.includes('?') ? '&' : '?') + queryString;
        }
      }
    }

    // 确保url以/开头
    const cleanUrl = url.startsWith('/') ? url : `/${url}`
    // 添加/api前缀
    const apiUrl = `/api${cleanUrl}`
    
    console.log('Request URL:', apiUrl)
    console.log('Request options:', {
      ...defaultOptions,
      ...requestOptions,
      headers: {
        ...defaultOptions.headers,
        ...requestOptions.headers,
      },
    })

    const response = await fetch(apiUrl, {
      ...defaultOptions,
      ...requestOptions,
      headers: {
        ...defaultOptions.headers,
        ...requestOptions.headers,
      },
    })

    const result = await response.json()
    
    // 检查响应状态
    if (result.code !== 0) {
      throw new Error(result.msg || '请求失败')
    }
    
    return result
  } catch (error: any) {
    console.error('Request failed:', error)
    // 如果是网络错误，显示更友好的错误信息
    if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      ElMessage.error(error.message || '网络错误')
    }
    return Promise.reject(error)
  }
}

export default request